package com.jxcq.tensquare.spit.controller;

import com.jxcq.tensquare.spit.pojo.Spit;
import com.jxcq.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author CalvinXCui
 * @date 2019- 10- 15 13:01
 */
@RestController
@CrossOrigin
@RequestMapping("spit")
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //判断当前用户是否已经点赞
        String userid = "";
        if(redisTemplate.opsForValue().get("thumbup_"+userid) != null){
            return new Result(true, StatusCode.REPEAT_ERROR,"不能重复点赞");
        }
        spitService.thumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_"+userid,true);//只是标识，可随便写
        return new Result(true, StatusCode.SUCCESS,"点赞成功");
    }

    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByParentid(@PathVariable String parentid, @PathVariable int page , @PathVariable int size){
        Page<Spit> pageData = spitService.findByParentid(parentid, page, size);
        return new Result(true, StatusCode.SUCCESS,"查询成功",new PageResult<Spit>(pageData.getTotalElements(),pageData.getContent()));
    }

    @GetMapping
    public Result findAll(){
        return new Result(true, StatusCode.SUCCESS,"查询成功",spitService.findAll());
    }
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        return new Result(true, StatusCode.SUCCESS,"查询成功",spitService.findById(spitId));
    }

    @PostMapping
    public Result save(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.SUCCESS,"保存成功");
    }

    @PutMapping("{spitId}")
    public Result update(@PathVariable String spitId, @RequestBody Spit spit){
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true, StatusCode.SUCCESS,"更新成功");
    }

    @DeleteMapping("{spitId}")
    public Result deleteById(@PathVariable String spitId){
        spitService.deleteById(spitId);
        return new Result(true, StatusCode.SUCCESS,"删除成功");
    }

}
